package MailFormat

import (
	"MailTimer/logger"
	"fmt"
	"github.com/sirupsen/logrus"
	"gopkg.in/gomail.v2"
	"strconv"
	"time"
)

//发送邮件
func SendMail(s Recipient) error {

	//定义邮箱服务器连接信息，网易邮箱、qq邮箱填授权码
	mailConn := map[string]string{
		"user": "17774898672@163.com",
		"pass": "CWIHBKBUXRNJBTYB",
		"host": "smtp.163.com",
		"port": "465",
	}

	port, _ := strconv.Atoi(mailConn["port"]) //转换端口类型为int
	m := gomail.NewMessage()

	m.SetHeader("From", m.FormatAddress(mailConn["user"], "系统提示"))
	m.SetHeader("To", s.MailTo...)     //发送给多个用户
	m.SetHeader("Subject", s.Subject)  //设置邮件主题
	m.SetBody("text/html", s.MailBody) //设置邮件正文

	d := gomail.NewDialer(mailConn["host"], port, mailConn["user"], mailConn["pass"])
	//开始发送
	err := d.DialAndSend(m)
	if err != nil {
		logger.MyLogger.WithFields(logrus.Fields{"DialAndSend": "拨号连接"}).Info("连接邮件server失败")
		return err
	}
	return nil
}

//获取收件人信息
func GetRecipient() Recipient {

	//定义收件人
	mailTo := []string{
		"1149246417@qq.com",
	}
	now := time.Now()
	t := fmt.Sprintf("%02d-%02d-%02d %02d:%02d:%02d", now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second())
	//邮件主题为"Hello"
	subject := "审单通知" + t
	body := fmt.Sprintf(`<div>
		<div>
			尊敬的领导，您好！
		</div>
		<div style="padding: 8px 40px 8px 50px;">
			<p>您有一笔单据,需要您审核</p>
		</div>
		<div>
			<p>此邮箱为系统邮箱，请勿回复。</p>
		</div>	
	</div>`)

	var r = Recipient{
		MailTo:   mailTo,
		Subject:  subject,
		MailBody: body,
	}
	return r
}
